<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { InfoStoreApi } from '#/api/spa/store';

import { Page, useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';

import { $t } from '#/locales';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { downloadFileFromBlobPart } from '@vben/utils';

import { deleteInfoStore, getInfoStoreWithGroup, getInfoStoreWithGroupPage } from '#/api/spa/store';
import { useSiteStore } from '#/stores/site';
import Form from './modules/form.vue';
import { useGridColumns, useGridFormSchema } from './data';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

// 站点管理store
const siteStore = useSiteStore();

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建门店 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑门店 */
function handleEdit(row: InfoStoreApi.InfoStore) {
  formModalApi.setData(row).open();
}

/** 删除门店 */
async function handleDelete(row: InfoStoreApi.InfoStore) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_key_msg',
  });
  try {
    await deleteInfoStore(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出表格 */
async function handleExport() {
  const data = await getInfoStoreWithGroup(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({
    fileName: '门店.xls',
    source: data as unknown as BlobPart,
  });
}

/** 解析站点信息 */
function parseSiteInfo(siteInfo: string) {
  try {
    const sites = JSON.parse(siteInfo);
    return Array.isArray(sites) ? sites : [];
  } catch (error) {
    console.error('解析站点信息失败:', error);
    return [];
  }
}

/** 处理站点点击 */
function handleSiteClick(site: any) {
  // 设置当前站点信息
  siteStore.setCurrentSiteInfo(site);
  
  // 跳转到站点管理页面（不显示siteId在URL中）
  siteStore.navigateToSite();
  
  message.success(`已切换到站点: ${site.siteName}`);
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getInfoStoreWithGroupPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<InfoStoreApi.InfoStore>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />

    <Grid table-title="门店列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['门店']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['spa:info-store:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['spa:info-store:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>
      <template #siteInfo="{ row }">
        <div v-if="row.siteInfo" class="site-tags">
          <a-tag
            v-for="site in parseSiteInfo(row.siteInfo)"
            :key="site.siteId"
            :title="`站点名称: ${site.siteName}\n站点域名: ${site.siteDomain || '无'}\n所属集团: ${site.groupName}\n状态: ${site.statusName}`"
            class="site-tag"
            @click="handleSiteClick(site)"
          >
            {{ site.siteName }}
          </a-tag>
        </div>
        <span v-else class="text-gray-400">未绑定站点</span>
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['spa:info-store:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['spa:info-store:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>

<style scoped>
.site-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 300px;
}

.site-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #d9d9d9;
  background-color: #fafafa;
}

.site-tag:hover {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
}
</style>
